package com.auto.survey.activity.monitoring.dao

import androidx.room.Dao
import androidx.room.Query
import androidx.room.Transaction
import com.auto.survey.activity.monitoring.entity.relations.PointWithCheckedPoint
import kotlinx.coroutines.flow.Flow

@Dao
interface PointWithCheckedPointDao {

    // 关联查询
    @Transaction
    @Query("SELECT * FROM MonitoringPoint WHERE id = :pointId")
    suspend fun getPointWithCheckedPoints(pointId: Int): PointWithCheckedPoint?

    @Transaction
    @Query("SELECT * FROM MonitoringPoint WHERE isWarning = 1")
    fun getWarningPointsWithCheckedPointsFlow(): Flow<List<PointWithCheckedPoint>>

    // 查询特定监测对象下且已采集数据的测点及其所有核验记录
    @Transaction
    @Query("""
        SELECT * FROM MonitoringPoint 
        WHERE stationId = :stationId 
        AND collected = 1  -- 添加 collected = true 条件
        ORDER BY measurementOrder ASC
    """)
    fun getCollectedPointsWithCheckedPointsByStationId(stationId: Int): Flow<List<PointWithCheckedPoint>>

    // 查询所有测点及其所有核验记录
    @Transaction
    @Query("SELECT * FROM MonitoringPoint ORDER BY createTime DESC")
    suspend fun getAllPointsWithCheckedPoints(): List<PointWithCheckedPoint>

    // 获取最近一个点及其最近的核验记录
    @Transaction
    @Query("""
        SELECT * FROM MonitoringPoint 
        ORDER BY createTime DESC 
        LIMIT 1
    """)
    suspend fun getLatestPointWithLatestCheck(): PointWithCheckedPoint?

    // 根据 pointId 获取指定点及其最近的核验记录
    @Transaction
    @Query("""
        SELECT * FROM MonitoringPoint 
        WHERE id = :pointId
    """)
    suspend fun getPointWithLatestCheck(pointId: Int): PointWithCheckedPoint?
}